﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace GrapeCity.ColinHan.Reflactor
{
    public class DomainHelper
    {
        public static AppDomain CreateDomainForWorker<T>(string domainName, out T worker)
            where T : MarshalByRefObject
        {
            string thisDirectory = GetLocalPath(Path.GetDirectoryName(typeof(T).Assembly.CodeBase));

            AppDomainSetup setup = new AppDomainSetup();
            setup.ApplicationBase = thisDirectory;
            AppDomain space = AppDomain.CreateDomain(domainName, null, setup);

            worker = space.CreateInstanceAndUnwrap(typeof(T).Assembly.FullName, typeof(T).FullName) as T;
            return space;
        }
        private static string GetLocalPath(string path)
        {
            Uri testUri = new Uri(path);
            if (testUri.Scheme == Uri.UriSchemeFile)
            {
                // For .net 3.5 sp1, we must do follow code if assembly is in local path. Otherwise, an File Not Found exception occur.
                // I test traveller in .net 4.0 bata 1, follow code is unnecessary.
                path = Uri.UnescapeDataString(testUri.AbsolutePath);
            }
            return path;
        }
    }
}
